//
//  ReleseGoodsViewController.m
//  PalmChangtu
//
//  Created by shaorui on 15/6/17.
//  Copyright (c) 2015年 PalmChangtu. All rights reserved.
//

#import "ReleseGoodsViewController.h"
#import "ProdectAddCell.h"
#import "ShareUserModel.h"

#import "MainTabbarController.h"
#import "JSONKit.h"
#import "Common.h"
#import "LoadingView.h"
#import "NetWarningView.h"
#import "AFNetworking.h"
#import "BaseUrlConfig.h"
#import "TestCollectionViewController.h"
#import "UIImageView+AFNetworking.h"
#import "UIImageView+WebCache.h"

#import "all_commodity_TypeModel.h"
#import "localJSONModel.h"
#import "MTLJSONAdapter.h"

@interface ReleseGoodsViewController ()

@end

@implementation ReleseGoodsViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}

-(void)viewDidAppear:(BOOL)animated
{

}
- (void)viewDidLoad {
    [super viewDidLoad];


    if ([self.strEditTemp isEqualToString:@"RelesedGoodsViewController"]) {

        [_v_Top.lalTitel setText:@"修改编辑商品"];



        self.textName.text = self.modelTemp.name;
        self.textPrice.text  = self.modelTemp.price;
        [self.btnTypeSelect setTitle:self.modelTemp.type forState:UIControlStateNormal];

        self.textView.text = self.modelTemp.content;
        self.textAfterSalesAddress.text = self.modelTemp.afterSalesAddress;

        self.btnDelete.hidden = NO;



    }
    else
    {
        [_v_Top.lalTitel setText:@"发布商品"];

        self.btnDelete.hidden = YES;
    }



    [_v_Top.btnGoback setHidden:NO];
    _v_Top.parentController = self.navigationController;
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(80,80);//定义大小，也可以在代理里面定义
    flowLayout.minimumInteritemSpacing=0.0f;//左右间隔
    flowLayout.minimumLineSpacing=0.0f;
    
        //      设置横向滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.sectionInset=UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.CollectionView.collectionViewLayout = flowLayout;
    self.CollectionView.delegate = self;
    self.CollectionView.dataSource = self;
    UINib *nibCellCollection = [UINib nibWithNibName:NSStringFromClass([ProdectAddCell class]) bundle:nil];
    
    [self.CollectionView registerNib:nibCellCollection forCellWithReuseIdentifier:[NSString stringWithFormat:@"%@",[ProdectAddCell class]]];
    
    _arrProdect  = [[NSMutableArray alloc] init];
    

    [self.btnTypeSelect removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];

    [self.btnTypeSelect addTarget:self action:@selector(btnTypeSelectAction:) forControlEvents:UIControlEventTouchUpInside];


    [self.btnSeondOnw removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];

    [self.btnSeondOnw addTarget:self action:@selector(btnClickSelectAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.btnSecond addTarget:self action:@selector(btnClickSelectAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.btnThird addTarget:self action:@selector(btnClickSelectAction:) forControlEvents:UIControlEventTouchUpInside];


    [self.btnOne addTarget:self action:@selector(btnClickSelectAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.btnTwo addTarget:self action:@selector(btnClickSelectAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.btnThree addTarget:self action:@selector(btnClickSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnFour addTarget:self action:@selector(btnClickSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnFive addTarget:self action:@selector(btnClickSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnSix addTarget:self action:@selector(btnClickSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnSeven addTarget:self action:@selector(btnClickSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnOther addTarget:self action:@selector(btnClickSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnCancle addTarget:self action:@selector(btnClickSelectAction:) forControlEvents:UIControlEventTouchUpInside];


    [self.btnRelese addTarget:self action:@selector(btnReleseAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.btnRelese addTarget:self action:@selector(btnReleseAction:) forControlEvents:UIControlEventTouchUpInside];


    [self.btnDelete addTarget:self action:@selector(btnProdectDeleteAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.btnDelete addTarget:self action:@selector(btnProdectDeleteAction:) forControlEvents:UIControlEventTouchUpInside];



    _viewTypeHidden.hidden  = YES;


       // Do any additional setup after loading the view from its nib.
}

-(void)btnTypeSelectAction:(UIButton *)btnTypeSelect
{
    _viewTypeHidden.hidden  = NO;


    

}
-(void)btnClickSelectAction:(UIButton *)ClickTypeSelect
{
    _viewTypeHidden.hidden  = YES;
    _btnTypeId = ClickTypeSelect.tag;


    [_btnTypeSelect setTitle:ClickTypeSelect.titleLabel.text forState:UIControlStateNormal];
    
    
}
-(void)btnReleseAction:(UIButton *)releseAction
{

    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];





    NSMutableArray  *mutablegoods_thumb = [[NSMutableArray alloc] init];

    for (UIImage * image in _arrProdect) {


        NSData* pictureData = UIImageJPEGRepresentation(image,0.5);
        NSString *encodedImageStr = [pictureData base64Encoding];//图片转码成为base64Encoding，
        [mutablegoods_thumb addObject:encodedImageStr];

    }


    NSDictionary *params =   nil;
    if ([self.strEditTemp isEqualToString:@"RelesedGoodsViewController"]) {


        params = @{

                   @"id":self.modelTemp.commodityId,
                   @"photo_str_arr":mutablegoods_thumb,
                   @"breands":[NSString stringWithFormat:@"%@",_btnTypeSelect.titleLabel.text],

                   @"content":[NSString stringWithFormat:@"%@",_textView.text],

                   @"afterSalesAddress":[NSString stringWithFormat:@"%@",_textAfterSalesAddress.text],
                   @"price":[NSString stringWithFormat:@"%@",self.textPrice.text],
                   @"type":[NSString stringWithFormat:@"%@",[NSNumber numberWithInteger:_btnTypeId]],
                   @"name":[NSString stringWithFormat:@"%@",self.textName.text],

                   @"userId":[NSString stringWithFormat:@"%@",shareUser.user.user_id],
                   @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                   @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId]



                   };


        [self ReleseGoodsRequest:params andUrl:update_commodityAction];

    }


    else
    {

        params = @{

                   
                   @"breands":[NSString stringWithFormat:@"%@",_btnTypeSelect.titleLabel.text],
                             @"photo_str_arr":mutablegoods_thumb,

                             @"content":[NSString stringWithFormat:@"%@",_textView.text],

                             @"afterSalesAddress":[NSString stringWithFormat:@"%@",_textAfterSalesAddress.text],
                             @"price":[NSString stringWithFormat:@"%@",self.textPrice.text],
                             @"type":[NSString stringWithFormat:@"%@",[NSNumber numberWithInteger:_btnTypeId]],
                             @"name":[NSString stringWithFormat:@"%@",self.textName.text],

                             @"userId":[NSString stringWithFormat:@"%@",shareUser.user.user_id],
                             @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                             @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId]



                            };
        [self ReleseGoodsRequest:params andUrl:publish_commodityAction];


    }


    
}

#pragma mark - UICollectionViewDataSource

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if ([_arrProdect count])
        {
          return  [_arrProdect count];
        }
    else
        return 1;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString * identifier = @"ProdectAddCell";
    
    ProdectAddCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    if ([self.strEditTemp isEqualToString:@"RelesedGoodsViewController"]) {



         if([_arrProdect count] !=0)
        {

            cell.imageProdect.image  = _arrProdect[indexPath.row];

            cell.imageProdect.userInteractionEnabled = YES;
        }
        else
        {
            [cell.imageProdect sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HostImage,self.modelTemp.photoUrl]] placeholderImage:[UIImage imageNamed:@"SDWebImageDefault.png"] ] ;

        }



        cell.imageProdect.userInteractionEnabled = YES;
        UILongPressGestureRecognizer *longPress =
        [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(whenlongPressClickImage:)];
        longPress.view.tag = indexPath.row;

        [cell.imageProdect addGestureRecognizer:longPress];

        [cell.btnDelete removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
        [cell.btnDelete addTarget:self action:@selector(btnDelete:) forControlEvents:UIControlEventTouchUpInside];






    }
    else

    {

    if ([_arrProdect count] == 0) {
        
        cell.imageProdect.image = [UIImage imageNamed:@"imageAdd"];
        cell.imageProdect.userInteractionEnabled = NO;
    }
    else if([_arrProdect count] !=0)
        {
        
        cell.imageProdect.image  = _arrProdect[indexPath.row];
        
        cell.imageProdect.userInteractionEnabled = YES;
        UILongPressGestureRecognizer *longPress =
        [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(whenlongPressClickImage:)];
        longPress.view.tag = indexPath.row;
        
        [cell.imageProdect addGestureRecognizer:longPress];
        
        [cell.btnDelete removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
        [cell.btnDelete addTarget:self action:@selector(btnDelete:) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        
        }
    
}
    return cell;
    
    
    
}
-(void)whenlongPressClickImage:(UILongPressGestureRecognizer*)PressClickImage
{
    
    
    CGPoint point = [PressClickImage locationInView:_CollectionView];
    
    NSIndexPath * indexPath = [self.CollectionView indexPathForItemAtPoint:point];
    
    if(indexPath == nil) return ;
    
    
    NSLog(@"%@",PressClickImage.view);
    ProdectAddCell * cell = (ProdectAddCell *) [self.CollectionView cellForItemAtIndexPath:indexPath];
    
    cell.btnDelete.tag = indexPath.row;
    
    
    cell.btnDelete.hidden  = NO;
    
    
    
}
#pragma mark - 删除图片

-(void)btnDelete:(UIButton *)btndelete
{
    
    
    
    NSInteger  intTag =  btndelete.tag;
    
    
    [_arrProdect removeObjectAtIndex:intTag];
    btndelete.hidden = YES;
    
    
    
    [self.CollectionView reloadData];
    
    
    
}
#pragma mark - UICollectionViewDelegate

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    ProdectAddCell * cell = (ProdectAddCell *) [collectionView cellForItemAtIndexPath:indexPath];
    if ([_arrProdect count]<=4) {
        QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        
        imagePickerController.limitsMinimumNumberOfSelection = YES;
        imagePickerController.maximumNumberOfSelection = 4;
        
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
        [self presentViewController:navigationController animated:YES completion:NULL];
        
        
    }
}

#pragma mark - QBImagePickerControllerDelegate

- (void)imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingMediaWithInfo:(id)info
{
    
    
    if(imagePickerController.allowsMultipleSelection) {
        
        
        NSMutableArray * mutaleArr = [[NSMutableArray alloc] init];
        
        
        NSArray *mediaInfoArray = (NSArray *)info;
        
        
        for (NSDictionary * dic in mediaInfoArray) {
            
            UIImage * image = [dic objectForKey:UIImagePickerControllerEditedImage];
            
            if (image == nil)
        {
                image = [dic objectForKey:UIImagePickerControllerOriginalImage];
                
                }
            [mutaleArr addObject:image];
            
        }
        
        _arrProdect = mutaleArr;
        
        
        
        NSLog(@"Selected %d photos", mediaInfoArray.count);
        
    } else {
        NSDictionary *mediaInfo = (NSDictionary *)info;
        NSLog(@"xSelected: %@", mediaInfo);
    }
    [self.CollectionView reloadData];
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController
{
    NSLog(@"Cancelled");
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (NSString *)descriptionForSelectingAllAssets:(QBImagePickerController *)imagePickerController
{
    return @"选择所有的图片";
}

- (NSString *)descriptionForDeselectingAllAssets:(QBImagePickerController *)imagePickerController
{
    return @"选择图片";
}

- (NSString *)imagePickerController:(QBImagePickerController *)imagePickerController descriptionForNumberOfPhotos:(NSUInteger)numberOfPhotos
{
    return [NSString stringWithFormat:@"一共有%@张", [NSNumber numberWithInteger:numberOfPhotos]];
}

- (NSString *)imagePickerController:(QBImagePickerController *)imagePickerController descriptionForNumberOfVideos:(NSUInteger)numberOfVideos
{
    return [NSString stringWithFormat:@"视频多少%d段",numberOfVideos];
}

- (NSString *)imagePickerController:(QBImagePickerController *)imagePickerController descriptionForNumberOfPhotos:(NSUInteger)numberOfPhotos numberOfVideos:(NSUInteger)numberOfVideos
{
    return [NSString stringWithFormat:@"一共多少%d图片、视频%d段", numberOfPhotos, numberOfVideos];
}






#pragma mark - network request publish_commodityAction

-(void)ReleseGoodsRequest:(NSDictionary *)params  andUrl:(NSString * )url
{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,url];




    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {


         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

         NSDictionary * dicRespon = responseObject;
         [self ReleseGoodsSuccessWith:dicRespon];

         [[LoadingView shareLoadingView] dismissAnimated:YES];



         
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];

}

-(void)ReleseGoodsSuccessWith:(NSDictionary *)dicRespon
{

    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
    {


              [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];

        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
    }
    
}


#pragma mark - 删除图片

-(void)btnProdectDeleteAction:(UIButton *)ProdectDeleteAction
{


    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];


     NSDictionary *   params = @{


                   @"id":[NSString stringWithFormat:@"%@",self.modelTemp.relesedgoodsID],
                   @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                   @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId]



                   };

    [self ProdectDeleteRequest:params andUrl:removeCommodityAction];

}

#pragma mark - network request publish_commodityAction

-(void)ProdectDeleteRequest:(NSDictionary *)params  andUrl:(NSString * )url
{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,url];




    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {


         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

         NSDictionary * dicRespon = responseObject;
         [self ProdectDeleteSuccessWith:dicRespon];

         [[LoadingView shareLoadingView] dismissAnimated:YES];




     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];

}

-(void)ProdectDeleteSuccessWith:(NSDictionary *)dicRespon
{

    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
    {


        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];

        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
    }
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
